var board= new Array();
var score=0;
var hasConflicted =new Array();
var hisStep = new Array();
var initFlag = false;

var windowLocalStorageKey0 = 'chrome2048byahoi-0';
var windowLocalStorageKey1 = 'chrome2048byahoi-1';

var startx=0;
var starty=0;
var endx=0;
var endy=0;

$(document).ready(function () {

	prepareForMobile();
    newgame();

    $('.newgamebtn').click(function(){
    	newgame();
    });
    $('.stepbackbtn').click(function(){
    	stepback();
    }); 
    $('.saveprobtn').click(function(){
    	savepro();
    });
    $('.loadprobtn').click(function(){
    	loadpro();
    });
    $('.creator-info').click(function(){
    	$('.game-info').fadeToggle('fast');
    }); 
    $('.cancle-btn').click(function(){
    	$('.game-info').fadeToggle('fast'); 
    });
    $('.loadprobtn').mouseover(function(){
    	$('.loadprolist div').empty();
    	if(!window.localStorage
    			|| window.localStorage.getItem(windowLocalStorageKey0) == null
    			|| window.localStorage.getItem(windowLocalStorageKey1) == null){
    		$('.loadprolist div').append('当前无存档！');
    	}else{
    		var obj = JSON.parse(window.localStorage.getItem('chrome2048byahoi-0'));
    		var _time = JSON.parse(window.localStorage.getItem('chrome2048byahoi-1'));
    		var _board = obj.pop(); 
    		var _score = _board.pop();
    		$('.loadprolist div').text('存档分数：'+_score+'|存档时间：'+_time);
    		if($('.loadprolist div').text().length>33){
    			var _width = $('.loadprolist').width() 
    					+ ($('.loadprolist div').text().length-33)*10;
    			$('.loadprolist').width(_width);
    		}
    	}
    	$('.loadprolist').fadeToggle('fast'); 
    });
    $('.loadprobtn').mouseout(function(){
    	$('.loadprolist').fadeToggle('fast'); 
    });
});
function prepareForMobile(){
    if(documentWidth>500){
        gridContainerWidth=500;
        cellSapce=20;
        cellSideLength=100;

    }

    $('#grid-container').css('width',gridContainerWidth-2*cellSapce);
    $('#grid-container').css('height',gridContainerWidth-2*cellSapce);
    $('#grid-container').css('padding',cellSapce);
    $('#grid-container').css('border-radius',0.02*gridContainerWidth);

    $('.grid-cell').css('width',cellSideLength);
    $('.grid-cell').css('height',cellSideLength);
    $('.grid-cell').css('border-radius',0.02*cellSideLength);
}

function newgame(){
    init();
    generateOneNumber();
    generateOneNumber();
}

function init(){
	board= new Array();
	score=0;
	hasConflicted =new Array();
	hisStep = new Array(); 
	initFlag = false;

    for(var i= 0 ;i< 4; i++) {
        for (var j = 0; j < 4; j++) {
            var gridCell = $("#grid-cell-"+ i +"-" + j);
            gridCell.css('top', getPosTop(i, j));
            gridCell.css('left', getPosLeft(i, j));
        }

    }


    for(var i= 0 ;i<4;i++) {
        board[i]=new Array();
        hasConflicted[i]=new Array();
        for (var j = 0; j < 4; j++) {
            board[i][j]=0;
            hasConflicted[i][j]=false;
        }
    }
    updateBoardView();
    updateScore(score);
}

function updateBoardView(){
	$('.game-over').hide();
    $(".number-cell").remove();
    for(var i= 0 ;i<4;i++) {
        for (var j = 0; j < 4; j++) {
           $("#grid-container").append('<div class="number-cell" id="number-cell-'+i+'-'+j+'"></div>');
            var theNumberCell = $("#number-cell-"+ i +"-" + j);

            if(board[i][j]==0){
                theNumberCell.css('width','0px');
                theNumberCell.css('height','0px');
                theNumberCell.css('top',getPosTop(i,j)+cellSideLength*0.5);
                theNumberCell.css('left',getPosLeft(i,j)+cellSideLength*0.5);
                theNumberCell.text("");
            }else{
                theNumberCell.css('width',cellSideLength);
                theNumberCell.css('height',cellSideLength);
                theNumberCell.css('top',getPosTop(i,j));
                theNumberCell.css('left',getPosLeft(i,j));
                theNumberCell.css('background-color',getNumberBackgroundColor(board[i][j]));
                theNumberCell.css('color',getNumberColor(board[i][j]));
                
                if(board[i][j] > 999 && board[i][j] < 10000){
                	theNumberCell.css('font-size', '40px');
                }
                else if(board[i][j] > 9999 && board[i][j] < 100000){
                	theNumberCell.css('font-size', '30px');
                }else{
                	theNumberCell.css('font-size',(0.6*cellSideLength-5)+'px');
                }
                theNumberCell.text(board[i][j]);
            }
            hasConflicted[i][j]=false;

        }

    }
    $('.number-cell').css('line-height',cellSideLength+'px');
}

function generateOneNumber(){
    if(nospace(board)){
    	return false;
    }

    var randx=parseInt(Math.floor(Math.random()*4));
    var randy=parseInt(Math.floor(Math.random()*4));
    var times=0;
    while (times<50){
        if (board[randx][randy]==0)
            break;
        var randx=parseInt(Math.floor(Math.random()*4));
        var randy=parseInt(Math.floor(Math.random()*4));
        times++;
    }
    if(times==50){
         for(var i=0;i<4;i++){
             for(var j=0;j<4;j++){
                 if(board[i][j]==0){
                     randx=i;
                     randy=j;
                 }
             }
         }
    }
    var randNumber=Math.random()<0.5? 2 : 4;
    board[randx][randy]=randNumber;
    showNumber(randx,randy,randNumber);
    saveHisStep();
    return true;
}

$(document).keydown(function(event){
    switch (event.keyCode){
        case 37:
            event.preventDefault();
            clickLeft();
            break; 
        case 38:
            event.preventDefault();
            clickUp();
            break;
        case 39:
            event.preventDefault();
            clickRight();
            break;
        case 40:
            event.preventDefault();
            clickDown();
            break;
        case 83:
        	event.preventDefault();
        	savepro();
        	window.close();
        	break;
        default:
            break;

    }

});

document.addEventListener('touchstart',function(event){
    event.preventDefault();
    startx=event.touches[0].pageX;
    starty=event.touches[0].pageY;
});

//document.activeElement('touchmove',function(event){
//    event.preventDefault();
//});

document.addEventListener();

document.addEventListener('touchend',function(event){

    event.preventDefault();
    endx=event.changedTouches[0].pageX;
    endy=event.changedTouches[0].pageY;

    var deltax=endx-startx;
    var deltay=endy-starty;

    if(Math.abs(deltax)<0.3*documentWidth&&Math.abs(deltay)<0.3*documentWidth){
        return ;
    }
    if(Math.abs(deltax)>Math.abs(deltay)){
        if(deltax>0){
        	clickRight();
        }else{
        	clickLeft();
        }
    }else{
        if(deltay>0){
        	clickDown();
        }else{
        	clickUp();
        }
    }
});


function clickLeft(){
	if(moveLeft()){
		generateOneNumber();
		isgameover();
    }
}
function clickRight(){
	if(moveRight()){
		generateOneNumber();
		isgameover();
    }
}
function clickUp(){
	if(moveUp()){
		generateOneNumber();
		isgameover();
    }
}
function clickDown(){
	if(moveDown()){
		generateOneNumber();
		isgameover();
    }
}


function isgameover(){
    if(nospace(board)&& nomove(board)){
        gameover();
    }
}

function gameover(){
    $('.game-over').fadeIn('slow');
}

function moveLeft(){
    if(!canMoveLeft(board)){
        return false;
    }
    for(var i= 0 ;i<4;i++) {
        for (var j = 1; j < 4; j++) {
            if(board[i][j]!=0){
                for(var k=0;k<j;k++){
                    if(board[i][k]==0&& noBlockHorizontal(i,k,j,board)){
                        showMoveAnimation(i,j,i,k);
                        board[i][k]=board[i][j];
                        board[i][j]=0;
                        break;
                    }
                    else if(board[i][k]==board[i][j]&& noBlockHorizontal(i,k,j,board)&&!hasConflicted[i][k])
                    {
                        showMoveAnimation(i,j,i,k);
                        board[i][k]+=board[i][j];
                        board[i][j]=0;
                        hasConflicted[i][k]=true;
                        score=score+board[i][k];
                        updateScore(score);
                        break;
                    }
                }
            }
        }
    }
    updateBoardView();
    return true;
}


function moveUp(){
    if(!canMoveUp(board)){
        return false;
    }
    for(var i= 1 ;i<4;i++) {
        for (var j = 0; j < 4; j++) {
            if(board[i][j]!=0){
                for(var k=0;k<i;k++){
                    if(board[k][j]==0&& noBlockVertical(j,k,i,board)){
                        showMoveAnimation(i,j,k,j);
                        board[k][j]=board[i][j];
                        board[i][j]=0;
                        break;
                    }
                    else if(board[k][j]==board[i][j]&& noBlockVertical(j,k,i,board)&&!hasConflicted[k][j])
                    {
                        showMoveAnimation(i,j,k,j);
                        board[k][j]+=board[i][j];
                        board[i][j]=0;
                        hasConflicted[k][j]=true;
                        score=score+board[k][j];
                        updateScore(score);
                        break;
                    }
                }
            }
        }
    }
    updateBoardView();
    return true;
}


function moveRight(){
    if(!canMoveRight(board)){
        return false;
    }
    for(var i= 0 ;i<4;i++) {
        for (var j = 2; j >-1; j--) {
            if(board[i][j]!=0){
                for(var k=3;k>j;k--){
                    if(board[i][k]==0&& noBlockHorizontal(i,j,k,board)){
                        showMoveAnimation(i,j,i,k);
                        board[i][k]=board[i][j];
                        board[i][j]=0;
                        break;
                    }
                    else if(board[i][k]==board[i][j]&& noBlockHorizontal(i,j,k,board)&&!hasConflicted[i][k])
                    {
                        showMoveAnimation(i,j,i,k);
                        board[i][k]+=board[i][j];
                        board[i][j]=0;
                        hasConflicted[i][k]=true;
                        score=score+board[i][k];
                        updateScore(score);
                        break;
                    }
                }
            }
        }
    }
    updateBoardView();
    return true;
}


function moveDown(){
    if(!canMoveDown(board)){
        return false;
    }
    for(var i=2 ;i>-1;i--) {
        for (var j = 0; j < 4; j++) {
            if(board[i][j]!=0){
                for(var k=3;k>i;k--){
                    if(board[k][j]==0&& noBlockVertical(j,i,k,board)){
                        showMoveAnimation(i,j,k,j);
                        board[k][j]=board[i][j];
                        board[i][j]=0;
                        break;
                    }
                    else if(board[k][j]==board[i][j]&& noBlockVertical(j,i,k,board)&&!hasConflicted[k][j])
                    {
                        showMoveAnimation(i,j,k,j);
                        board[k][j]+=board[i][j];
                        board[i][j]=0;
                        hasConflicted[k][j]=true;
                        score=score+board[k][j];
                        updateScore(score);
                        break;
                    }
                }
            }
        }
    }
    updateBoardView();
    return true;
}



 



